package chat.ourGamePackage;

import javax.swing.*;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.*;
import java.awt.image.BufferedImage;

public class DrawPanel extends JPanel implements KeyListener
{
	BufferedImage buffer;
	Image backgroundImg;
	Entity player;
	Entity enemy;
	
	public DrawPanel()
	{
		setIgnoreRepaint(true);
		addKeyListener(this);
		setFocusable(true);
		
		backgroundImg = Toolkit.getDefaultToolkit().getImage("background.jpg");
	}

	public void keyTyped(KeyEvent e)
	{
		// TODO Auto-generated method stub
		
	}

	public void keyPressed(KeyEvent e)
	{
		int key = e.getKeyCode();
		
		if(key == KeyEvent.VK_LEFT)
		{
			player.left = true;
		}
		if (key == KeyEvent.VK_RIGHT)
		{
			player.right = true;
		}
		if (key == KeyEvent.VK_UP)
		{
			player.up = true;
		}
		if (key == KeyEvent.VK_DOWN)
		{
			player.down = true;
		}
		
	}

	public void keyReleased(KeyEvent e)
	{
		int key = e.getKeyCode();
		
		if(key == KeyEvent.VK_LEFT)
		{
			player.left = false;
		}
		if (key == KeyEvent.VK_RIGHT)
		{
			player.right = false;
		}
		if (key == KeyEvent.VK_UP)
		{
			player.up = false;
		}
		if (key == KeyEvent.VK_DOWN)
		{
			player.down = false;
		}
		
	}
	
	public void Initialize()
	{
		buffer = new BufferedImage(800,600,BufferedImage.TYPE_INT_RGB);
		player = new Entity(100,100);
		enemy = new Entity(400,400);
	}

	public void update()
	{
		player.move();
	}

	public void checkCollisions()
	{
		if(player.getBounds().intersects(enemy.getBounds()))
		{
			player.collision = true;
		}
		else
		{
			player.collision = false;
		}
	}

	public void drawBuffer()
	{
		Graphics2D b = buffer.createGraphics();
		//b.drawImage(backgroundImg,0,0,null);
		b.setColor(Color.black);
		b.fillRect(0,0,800,600);
		
		// Enemy and player draw
		if(player.collision == false)
		{
			b.setColor(Color.red);
			b.fillRect(player.getX(), player.getY(), player.getWidth(), player.getHeight());
			b.setColor(Color.blue);
			b.fillRect(enemy.getX(),enemy.getY(),enemy.getWidth(),enemy.getHeight());
			b.dispose();
		}
		else
		{
			b.setColor(Color.white);
			b.drawString("COLLISION", 350,300);
			b.dispose();
		}
	}

	public void drawScreen()
	{
		Graphics2D g = (Graphics2D)this.getGraphics();
		g.drawImage(buffer,0,0,this);
		Toolkit.getDefaultToolkit().sync();
		g.dispose();
	}

	public void startGame()
	{
		Initialize();
		while(true)
		{
			try
			{
		        update();
		        checkCollisions();
		        drawBuffer();
		        drawScreen();
		        Thread.sleep(10);				
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
	}
}
